package com.example.resourceSharingPlatform.config.security.jwt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权用
 * 验证token是否有效
 * 赋给UserDetails权限
 */

@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {
	
	//用于操纵token的类
	@Autowired
    private JwtTokenUtils jwtTokenUtils;

	//操纵users实体,里面现在只有loadUserByUsername(String username),根据用户名填充出一个users实体
    @Autowired
    private UserDetailsService userDetailServiceImpl;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        
    	//http  请求头中的token
        String token = request.getHeader(jwtTokenUtils.getHeader());
        
        if (token!=null && token.length()>0) {
        	//从token获取用户名
            String username = jwtTokenUtils.getUsernameFromToken(token);
            if (username != null && SecurityContextHolder.getContext().getAuthentication()==null) {
            	//根据用户名生成userDetails实体
                UserDetails userDetails = userDetailServiceImpl.loadUserByUsername(username);
              //JwtTokenUtils.validateToken(String token, UserDetails userDetails)
               //验证token是否有效
               if (jwtTokenUtils.validateToken(token, userDetails)) {
                    /*
                     * 给使用该JWT令牌的用户进行授权
                     * ！！！这是给UserDetails授权的语句
                     */
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    //设置用户身份授权
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
